import OrderableCollection from "../../base/models/OrderableCollection.js";
import TaskGroupModel from './TaskGroupModel.js';
import {
    ajax_call
} from '../../tools.js';
import Radio from 'backbone.radio';


const TaskGroupCollection = OrderableCollection.extend({
    model: TaskGroupModel,
    initialize: function (options) {
        TaskGroupCollection.__super__.initialize.apply(this, options);
        this.on('saved', this.channelCall);
        this.on('destroyed', this.channelCall);
    },
    channelCall: function () {
        var channel = Radio.channel('facade');
        channel.trigger('changed:task');
    },
    afterLoadFromCatalog() {
        let this_ = this
        this.fetch().then(function () {
            this_.trigger('saved')
        });
    },
    load_from_catalog: function (sale_products) {
        var serverRequest = ajax_call(
            this.url + '?action=load_from_catalog', {
                sale_products: sale_products
            },
            'POST'
        );
        serverRequest.then(this.afterLoadFromCatalog.bind(this));
    },
    ht: function () {
        var result = 0;
        this.each(function (model) {
            result += model.ht();
        });
        return result;
    },
    tvaParts: function () {
        var result = {};
        this.each(function (model) {
            var tva_parts = model.tvaParts();
            _.each(tva_parts, function (value, key) {
                if (key in result) {
                    value += result[key];
                }
                result[key] = value;
            });
        });
        return result;
    },
    ttc: function () {
        var result = 0;
        this.each(function (model) {
            result += model.ttc();
        });
        return result;
    },
    validate: function () {
        var result = this.constructor.__super__.validate.call(this);
        if (this.models.length === 0) {
            result['groups'] = "Veuillez ajouter au moins un chapitre";
            this.trigger(
                'validated:invalid',
                this, {
                    groups: "Veuillez ajouter au moins un chapitre"
                }
            );
        }
        return result;
    }
});
export default TaskGroupCollection;